<!-- 单文件上传控件 -->
<template>
  <a-upload
    action="/"
    :disabled="disabled"
    @change="onChange"
    @success="success"
    @error="error"
    :tip="tip"
    :file-list="[currFile]"
    :auto-upload="false"
    @before-upload="beforeUpload"
    ref="uploadRef"
  />
</template>

<script lang="ts" setup>
import { PostFile } from '@/apis/management/base';
import { Message, Modal } from '@arco-design/web-vue';

const props = withDefaults(
  defineProps<{
    props: { [propName: string]: any };
    name?: string;
    required?: boolean;
    oneValue: any;
    disabled?: boolean;
    regex?: {
      [name: string]: {
        role: any;
        name: any;
      };
    };
  }>(),
  {}
);
const emit = defineEmits(['update:oneValue']);
const modelValue = computed({
  get: () => {
    return props.oneValue;
  },
  set: (val) => {
    emit('update:oneValue', val);
  }
});

//复制一份props
const getProps = computed(() => {
  return props.props;
});

const tip = `只能上传单个文件`;

let uploadRef = ref();

// 储存当前文件
let currFile = ref<any>({
  uid: '-1',
  name: '',
  url: ''
});

onMounted(() => {
  if (
    modelValue.value !== undefined &&
    modelValue.value[0] !== '' &&
    modelValue.value
  ) {
    currFile.value = JSON.parse(modelValue.value);
  }
});

// 文件上传
const onChange = async (_, currentFile: any) => {
  try {
    currFile.value = {
      ...currentFile
      // url: URL.createObjectURL(currentFile.file),
    };
    console.log(currFile.value);

    let temp = new FormData();
    temp.append('data', currentFile.file);
    // const url = await PostFile(temp);
    // modelValue.value = JSON.stringify({
    //   url,
    //   uid: currFile.value.uid,
    //   name: currFile.value.name
    // });
    uploadRef.value.submit();
    // let index = url.lastIndexOf('\/');
    // modelValue.value = url.substring(index + 1, url.length);
  } catch (error: unknown) {
    console.log(error);
  }
};

const onProgress = (currentFile) => {
  currFile.value = currentFile;
};

const customRequest = async (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option;
  let temp = new FormData();
  temp.append('data', fileItem.file);
  const url = await PostFile(temp);
  Message.success('上传文件成功！');
  modelValue.value = JSON.stringify({
    url,
    uid: currFile.value.uid,
    name: currFile.value.name
  });

  // const xhr = new XMLHttpRequest();
  // if (xhr.upload) {
  //   xhr.upload.onprogress = function (event) {
  //     let percent;
  //     if (event.total > 0) {
  //       // 0 ~ 1
  //       percent = event.loaded / event.total;
  //     }
  //     onProgress(percent, event);
  //   };
  // }
  // xhr.onerror = function error(e) {
  //   onError(e);
  // };
  // xhr.onload = function onload() {
  //   if (xhr.status < 200 || xhr.status >= 300) {
  //     return onError(xhr.responseText);
  //   }
  //   onSuccess(xhr.response);
  // };

  // const formData = new FormData();
  // formData.append(name || 'file', fileItem.file);
  // xhr.open('post', 'http://192.168.31.129:39001/basis/file/upload', true);
  // xhr.send(formData);

  // return {
  //   abort() {
  //     xhr.abort();
  //   }
  // };
};

// 上传之间校验
const beforeUpload = (file: any) => {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      title: 'beforeUpload',
      content: `确认上传 ${file.name}`,
      onOk: () => resolve(true),
      onCancel: () => reject('cancel')
    });
  });
};

// 成功时候调用
const success = (fileItem: any) => {
  Message.success('上传文件成功！');
};

// 失败的时候调用
const error = (fileItem: any) => {
  Message.error('上传文件失败，请重新上传！ ');
};
</script>

<style scoped lang="less"></style>
